'use strict';
import * as vscode from 'vscode';
import { getPuncpairs } from './helpers';

let puncpairs: any;
let correction: boolean;
correction = true;
let myStatusBarItem: vscode.StatusBarItem;

export function activate({ subscriptions }: vscode.ExtensionContext) {
  const myCommandId = 'autopunc.toggleCorrect';
  subscriptions.push(vscode.commands.registerCommand(myCommandId, () => {
    correction = !correction;
    if (correction) {
      myStatusBarItem.text = '$(check) 标点自动转换';
    } else {
      myStatusBarItem.text = '$(chrome-close) 标点自动转换';
    }
  }));
  
  myStatusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 300);
  myStatusBarItem.text = '$(check) 标点自动转换';
  myStatusBarItem.show();
  myStatusBarItem.command = myCommandId;
  subscriptions.push(myStatusBarItem);

//   try {
    puncpairs = puncpairs || getPuncpairs();
    vscode.workspace.onDidOpenTextDocument(() => {
      puncpairs = puncpairs || getPuncpairs();
    });
    vscode.workspace.onDidChangeTextDocument(event => {
      puncpairs = puncpairs || getPuncpairs();
      if (correction) {
        correctPunc(event);
        // 把中文省略号 …… 转换的两个 ^^ 去掉一个
        correctDup(event);
      }
    });
//   } catch (error) {
//     console.log(error);      
//   }
  
  // vscode.workspace.onDidChangeConfiguration(e => {
  //   if (e.affectsConfiguration('auto-correct')) {
  //     config = getConfig();
  //   }
  // });
}

// this method is called when your extension is deactivated
export function deactivate() {}

function correctPunc(event: vscode.TextDocumentChangeEvent): void {
  if (!event.contentChanges.length) {
    return;
  }

  let lastChr = event.contentChanges[0].text;

  const editor = vscode.window.activeTextEditor;
  if (!editor) {
    return;
  }

  const keys = Object.keys(puncpairs);

  if (keys.includes(lastChr)) {
    editor.edit(
      editBuilder => {
        const contentChangeRange = event.contentChanges[0].range;
        const startLine = contentChangeRange.start.line;
        const startCharacter = contentChangeRange.start.character;
        let start: vscode.Position;
        if (lastChr === '…' || lastChr === '—') {
          start = new vscode.Position(startLine, startCharacter - 1);
        } else {
          start = new vscode.Position(startLine, startCharacter);
        }
        const end = new vscode.Position(startLine, startCharacter + 1);

        editBuilder.delete(new vscode.Range(start, end));
        // editBuilder.insert(start, puncpairs[lastChr]);
      },
      {
        undoStopAfter: false,
        undoStopBefore: false,
      }
    ).then(
      () => {
        vscode.commands.executeCommand("type", { text: puncpairs[lastChr] });
      }
    );    
  }
}

function correctDup(event: vscode.TextDocumentChangeEvent): void {
  if (!event.contentChanges.length) {
    return;
  }

  const editor = vscode.window.activeTextEditor;
  if (!editor) {
    return;
  }

  const contentChangeRange = event.contentChanges[0].range;
  const startLine = contentChangeRange.start.line;
  const startCharacter = contentChangeRange.start.character;
  const start = new vscode.Position(startLine, startCharacter - 1);
  const end = new vscode.Position(startLine, startCharacter + 1);
  const text = editor.document.getText(
    new vscode.Range(start, end)
  );
  // console.log(text);

  if (text === '^^') {
    editor.edit(
      editBuilder => {
        const newStart = new vscode.Position(startLine, startCharacter);
        if (startCharacter) {
          editBuilder.delete(new vscode.Range(newStart, end));
        }
      },
      {
        undoStopAfter: false,
        undoStopBefore: false,
      }
    );    
  }
}
